

const express = require('express');
const app = express();
// 添加 express.json() 中间件来解析 JSON 请求体
const port = 3000;
const WebSocket = require('ws');

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: port });
// 定义存储连接的客户端的数组
const clients = [];

// 监听连接事件
wss.on('connection', function connection(ws) {
  console.log('Client connected');

  // 将新连接的客户端添加到数组中
  clients.push(ws);

  // 监听消息事件
  ws.on('message', function incoming(messageText) {

    // 循环遍历所有客户端，将收到的消息发送给每个客户端
    clients.forEach(client => {
      const obj = JSON.parse(messageText.toString())
      const newObj = {}
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        newObj.name = obj.name
        newObj.userId = obj.userId
        newObj.msg = obj.msg
        client.send(JSON.stringify(newObj));
      }
    });
  });

  // 监听断开事件
  ws.on('close', function close() {
    console.log('Client disconnected');

    // 当有客户端断开连接时，从数组中移除对应的客户端
    clients.splice(clients.indexOf(ws), 1);
  });
});